package service

import (
	"encoding/json"
	"errors"
	"haiqiu-go-admin/dao"
	"haiqiu-go-admin/entity"
	"haiqiu-go-admin/entity/dto"
	"haiqiu-go-admin/entity/vo"
	"haiqiu-go-admin/result"
	"haiqiu-go-admin/utils"
	"log"
	"net/http"
	"strconv"
	"time"
)

// PostById 根据ID查询数据
func PostById(w http.ResponseWriter, r *http.Request) (any, error) {
	formatJson := utils.GetParamsFormatJson(w, r)
	postIdStr := formatJson["id"][0]
	postId, err := strconv.ParseInt(postIdStr, 10, 64)
	if err != nil {
		panic(err)
		return nil, err
	}
	post, err := dao.PostById(postId)
	if err != nil {
		return nil, err
	}
	return &post, nil
}

// PostPage 分页查询
func PostPage(w http.ResponseWriter, r *http.Request) (any, error) {
	formatJson, err := utils.GetBodyFormatJson(w, r)
	if err != nil {
		return nil, errors.New(result.ParamsErr)
	}
	var page dto.PositionQueryDto
	err = json.Unmarshal(formatJson, &page)
	if err != nil {
		log.Println(err)
	}
	count := dao.PostPageCount(page)
	if count == 0 {
		return vo.PageData{Total: 0}, nil
	}
	var pageData vo.PageData
	list, err := dao.PostPageList(page)
	pageData.Data = list
	pageData.Total = count
	pageData.PageIndex = page.PageIndex
	pageData.PageSize = page.PageSize
	if err != nil {
		return nil, err
	}
	return pageData, nil
}

// PostAdd 新增数据
func PostAdd(w http.ResponseWriter, r *http.Request) (any, error) {
	formatJson, err := utils.GetBodyFormatJson(w, r)
	if err != nil {
		return nil, err
	}
	var sysPost = entity.SysPosition{}
	err = json.Unmarshal(formatJson, &sysPost)
	if err != nil {
		return nil, err
	}
	var nowTime = time.Now()
	sysPost.CreateTime = &nowTime
	sysPost.UpdateTime = &nowTime
	add, err := dao.PostAdd(&sysPost)
	if err != nil {
		return nil, err
	}
	return add, nil
}

// PostUpdate 根据ID更新数据
func PostUpdate(w http.ResponseWriter, r *http.Request) (any, error) {
	formatJson, err := utils.GetBodyFormatJson(w, r)
	if err != nil {
		return nil, err
	}
	var sysPost = entity.SysPosition{}
	err = json.Unmarshal(formatJson, &sysPost)
	if err != nil {
		return nil, err
	}
	var nowTime = time.Now()
	sysPost.UpdateTime = &nowTime
	add, err := dao.PostUpdate(&sysPost)
	if err != nil {
		return nil, err
	}
	return add, nil
}

// PostDeleteBatch 批量删除数据
func PostDeleteBatch(w http.ResponseWriter, r *http.Request) (any, error) {
	formatJson, err := utils.GetBodyFormatJson(w, r)
	if err != nil {
		return nil, err
	}
	var ids []int64
	err = json.Unmarshal(formatJson, &ids)
	if err != nil {
		return nil, err
	}

	add, err := dao.PostDeleteBatch(ids)
	if err != nil {
		return nil, err
	}
	return add, nil
}

// PostList 查询所有数据
func PostList(w http.ResponseWriter, r *http.Request) (*[]entity.SysPosition, error) {
	postList, err := dao.PostList()
	if err != nil {
		log.Println(err.Error())
		return nil, err
	}
	return postList, nil
}
